<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use Laravel\Socialite\Facades\Socialite;
use Illuminate\Support\Facades\Auth;
use App\User;

class SocialController extends Controller
{
    //
    public function loginByGithub()
    {
        return Socialite::driver('github')->redirect();
    }
    public function authGithub ()
    {
        $user = Socialite::driver('github')->user();
        $dbUser = User::where('email',$user->email)->first();
        if($dbUser) {
            $dbUser->github_id = $user->id;
            $dbUser->github_name = $user->name;
            $dbUser->github_avatar = $user->avatar;
            $dbUser->github_nickname = $user->nickname;
            $dbUser->github_email = $user->email;
            $dbUser->github_token = $user->token;
            $dbUser->github_json = json_encode($user->user);
            $dbUser->save();

        } else {
            $dbUser = new User();
            $dbUser->github_id = $user->id;
            $dbUser->email = $user->email;
            $dbUser->github_id = $user->id;
            $dbUser->github_name = $user->name;
            $dbUser->github_avatar = $user->avatar;
            $dbUser->github_nickname = $user->nickname;
            $dbUser->github_email = $user->email;
            $dbUser->github_token = $user->token;
            $dbUser->github_json = json_encode($user->user);
            $dbUser->save();
        }
        Auth::login($dbUser);
        return redirect('/');
    }



    public function loginByWeibo()
    {
//        dd(config('services.weibo'));
        return Socialite::driver('weibo')->redirect();
    }

    public function authWeibo()
    {
        $user = Socialite::driver('weibo')->user();
        $wbId = $user->id;
        $wMail = $wbId.'@weibo.com';

        $dbUser = User::where('email',$wMail)->first();
//        dd($dbUser,$wMail);
        if($dbUser) {
            $dbUser->weibo_id =  $wbId;
            $dbUser->weibo_avatar = $user->avatar;
            $dbUser->weibo_nickname = $user->nickname;
            $dbUser->weibo_name = ($user->user['name']);
            $dbUser->weibo_token = $user->token;
            $dbUser->name = ($user->user['name']);
            $dbUser->weibo_json = json_encode($user->user);
            $dbUser->save();

        } else {
            $dbUser = new User();
            $dbUser->email = $wMail;
            $dbUser->name = ($user->user['name']);
            $dbUser->weibo_id =  $wbId;
            $dbUser->weibo_avatar = $user->avatar;
            $dbUser->weibo_nickname = $user->nickname;
            $dbUser->weibo_name = ($user->user['name']);
            $dbUser->weibo_token = $user->token;
            $dbUser->weibo_json = json_encode($user->user);
            $dbUser->save();
        }
        Auth::login($dbUser);
        return redirect('/');    }

}
